﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;

namespace Web.Product
{
    public partial class Products : System.Web.UI.Page
    {
        static USER user;
        static long? assignedtoID = null;
        static List<PRODUCT_DETAIL> products;
        static ROLE r;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            user = (USER)Session["User"];
            assignedtoID = null;
            if (user != null)
            {
                DateTime dt = DateTime.Now;
                DateTime dt2 = dt.AddMonths(-3);
                dpDateCreatedFrom.SelectedDate = new DateTime(dt2.Year, dt2.Month, 1);
                dpDateCreatedTo.SelectedDate = DateTime.Now;
                r = RoleService.GetRoleByID((long)user.ROLE_ID);
                if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                {
                    assignedtoID = user.ID;
                    divAssignTo.Visible = false;
                    lbtnExportToCSV.Visible = false;
                }

                LoadAllUser();
                products = getDataSource(dpDateCreatedFrom.SelectedDate, dpDateCreatedTo.SelectedDate.Value.AddHours(24), "", "", null, assignedtoID);
                RadGrid1.DataSource = products;
                RadGrid1.DataBind();
            }
        }
        private void LoadAllUser()
        {
            ddlAssignedTo.Items.Clear();
            List<USER> users = UserService.ListAll();
            if (users != null)
            {
                foreach (USER u in users)
                {
                    ddlAssignedTo.Items.Add(new RadComboBoxItem(u.SUR_NAME + " " + u.NAME, u.ID.ToString()));
                }
            }
            ddlAssignedTo.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }
        private List<PRODUCT_DETAIL> getDataSource(DateTime? dateFrom, DateTime? dateTo, string productName, string partNumber, double? unitPrice, long? assignedtoID)
        {
            List<PRODUCT_DETAIL> dt = ProductService.GetProductByCondition(dateFrom, dateTo, productName, partNumber, unitPrice, assignedtoID);
            if (dt == null)
            {
                dt = new List<PRODUCT_DETAIL>();
            }
            return dt;
        }
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = products;
        }

        protected void btnSearch_ServerClick(object sender, EventArgs e)
        {
            double? p = null;
            if (txtUnitPrice.Text.Trim() != "")
                p = Convert.ToDouble(txtUnitPrice.Text);
            if (divAssignTo.Visible)
            {
                long? at = Convert.ToInt64(ddlAssignedTo.SelectedValue);
                assignedtoID = at == -1 ? null : at;
            }
            products = getDataSource(dpDateCreatedFrom.SelectedDate, dpDateCreatedTo.SelectedDate.Value.AddHours(24), txtProductName.Text.Trim(), txtPartNumber.Text.Trim(), p, assignedtoID);
            RadGrid1.DataSource = products;
            RadGrid1.DataBind();
        }
        protected void btnAddProduct_ServerClick(object sender, EventArgs e)
        {
            Response.Redirect("AddNewProduct.aspx");
        }

        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridPagerItem)
            {
                GridPagerItem oGridPagerItem = (GridPagerItem)e.Item;
                RadComboBox oRadComboBox = (RadComboBox)oGridPagerItem.FindControl("PageSizeComboBox");
                oRadComboBox.Width = Unit.Pixel(50);
            }
        }
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            GridDataItem dataItem = e.Item as GridDataItem;
            switch (e.CommandName)
            {
                case "Edit":
                    Response.Redirect("EditProduct.aspx?id=" + dataItem["ID"].Text);
                    break;
                case "Delete":
                    long productID = Convert.ToInt64(dataItem["ID"].Text);
                    System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)dataItem["GridImageColumn"].Controls[0];
                    string sImg = img.ImageUrl;
                    int deleteProduct = ProductService.DeleteProduct(productID);
                    if (deleteProduct == 1)
                    {
                        products.Remove(products.Where(x => x.ID == productID).FirstOrDefault<PRODUCT_DETAIL>());
                        System.IO.File.Delete(Server.MapPath(sImg));
                        RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Delete product successful !" + "');");
                        //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Delete product successful !');", true);
                    }
                    else
                        RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not delete this product !" + "');");
                        //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not delete product !');", true);
                    break;
                default:
                    break;
            }

        }
        protected void lbtnExportToCSV_ServerClick(object sender, EventArgs e)
        {
            RadGrid1.ExportSettings.IgnorePaging = true;
            RadGrid1.ExportSettings.OpenInNewWindow = true;
            RadGrid1.ExportSettings.UseItemStyles = true;
            DateTime dt = DateTime.Now;
            RadGrid1.ExportSettings.FileName = "Products_" + dt.Year + dt.Month + dt.Day;
            RadGrid1.MasterTableView.GetColumn("TOOLS").Display = false;
            RadGrid1.MasterTableView.ExportToCSV();
        }

        protected void RadGrid1_PreRender(object sender, EventArgs e)
        {
            if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
            {
                RadGrid1.MasterTableView.GetColumn("ASSIGN_TO").Visible = false;
                RadGrid1.MasterTableView.GetColumn("PRODUCT_NAME").ItemStyle.Width = Unit.Percentage(20);
                RadGrid1.MasterTableView.GetColumn("PRODUCT_NAME").HeaderStyle.Width = Unit.Percentage(20);
                RadGrid1.MasterTableView.GetColumn("SERIAL_NO").ItemStyle.Width = Unit.Percentage(20);
                RadGrid1.MasterTableView.GetColumn("SERIAL_NO").HeaderStyle.Width = Unit.Percentage(20);
            }
        }
    }
}